<?php 
class CartWS_Model_Zone extends Ext_Db_Table
{
	protected $_name = 'sc_zone';
	protected $_sequence = 'sc_zone_seq';
	protected $_dependentTables = array( 
		'Default_Model_Address', 
		'Default_Model_ShippingCost'
	);
	public function getSelectWithDescr( $zone = null, $parentId = null)
	{
		
		$query = $this->getAdapter()->select()
			->from( array( 'z1' => 'sc_zone' ), 
				array( 'z1.*', 'fend_date' => "to_char( z1.end_date, '". self::DEFAULT_DATE_FORMAT. "')" )
			);
		if( $zone == 'country' ) {
			$query->where( 'z1.parent_zone_id = 0' ); 
		} else {
			$query = $query->join( 
				array( 'z2' => 'sc_zone' )
				, 'z2.zone_id = z1.parent_zone_id'
				, array( 'zone_parent_name' => 'z2.name ' ) 
				)
			->where( 'z1.parent_zone_id = ?', $parentId);
		}

		return $query;
	}
	public function findParentParent( $id ) 
	{
		return $this->find( $id )->current()->parent_zone_id;
	}
	
	public function getZone( $parentId )
	{
		$zone = ( $parentId == 0 )?'country':null;
		$rowset = $this->getAdapter()->fetchAll( 
			$this->getSelectWithDescr($zone, $parentId )
		);
		if( count( $rowset )) {
			return $rowset;
		}else {
			return array();
		}
	}
	
	public function getInheritance( $zoneId ) 
	{
		$query= "
			SELECT za.zone_id commune_id,za.name commune_name,  zb.zone_id city_id,zb.name city_name,
			zc.zone_id county_id,za.name county_name,  zd.zone_id country_id, zd.name country_name
			FROM sc_zone za 
			INNER JOIN sc_zone zb ON zb.zone_id = za.parent_zone_id
			INNER JOIN sc_zone zc ON zc.zone_id = zb.parent_zone_id
			INNER JOIN sc_zone zd ON zd.zone_id = zc.parent_zone_id
			WHERE za.zone_id = " . $zoneId;
		$row = $this->getAdapter()->fetchRow($query);
		if( count( $row))  {
			return $row;
		}
		throw new Ext_Exception( 'La zona es incorrecta' );
	}
}